package com.mijie.homi.inteceptor;

import java.util.Enumeration;
import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mijie.core.Status;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.service.session.SessionService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.HttpUtil;
import com.mijie.util.IPUtil;


public class AccessControlInteceptor implements HandlerInterceptor {
	
	private static Logger logger = Logger.getLogger(AccessControlInteceptor.class);
	
	private SessionService sessionService;
	
	public void setSessionService(SessionService sessionService) {
		this.sessionService = sessionService;
	}


	private static HashSet<String> openURLSet = new HashSet<String>();
	static{
		openURLSet.add("/user/check_nickname.json");
		openURLSet.add("/user/register.json");
		openURLSet.add("/user/login.json");
		openURLSet.add("/user/info.json");
		openURLSet.add("/user/list/nick_name.json");
		openURLSet.add("/sys/password/reset/apply.json");
		openURLSet.add("/sys/protocol.json");
		openURLSet.add("/report/crash.json");
		openURLSet.add("/report/terminal/active.json");
		openURLSet.add("/report/trytosignup.json");
		openURLSet.add("/topic/opinion/list.json");
		openURLSet.add("/topic/get.json");
	}
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		request.setAttribute("statStart", System.currentTimeMillis());
		boolean next = false;
		String servletPath = request.getServletPath();
		if(servletPath.startsWith("/internal/")){
			next = IPUtil.isInternalIp(HttpUtil.getIp(request));
			logger.info("[ip:"+HttpUtil.getIp(request)+"] "+(next?" is ":"not a ")+" internal ip.request url:"+servletPath);
		}else if(servletPath.endsWith(".shtml") || 
				   servletPath.startsWith("/stat/") ||
				   servletPath.startsWith("/user/thirdpart/") || 
				   openURLSet.contains(servletPath) ){
				next = true;
		}else{
			next = verfiy(request,response);
		}
		return next;
	}
	

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Long start = (Long) request.getAttribute("statStart");
		logger.info("[userId:"+ServerHelper.getUserId(request)+"]request["+request.getMethod()+","+HttpUtil.getIp(request)+"] "+request.getServletPath()+"?"+request.getQueryString()+" spend "+(System.currentTimeMillis()-start)+" millis.");
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView model) throws Exception {
	}
	
	
	private boolean verfiy(HttpServletRequest request,HttpServletResponse response){
		boolean flag = false;
		String token = request.getHeader("token");
		if(token!=null){
			Integer userId = sessionService.getUserIdByToken(token);
			if(userId!=null){
				request.setAttribute(ServerHelper.REQUEST_ATTR_USERID,userId);
				flag = true;
			}else{
				logger.info("[AUTH_FAIL] path: "+request.getServletPath()+",token: "+token);
				Status status = new Status(request,response);
				status.setCode(HomiStatusCode.AUTH_FAIL);
				status.write();
			}
		}else{
			logger.info("[TOKEN_ABSENT] path: "+request.getServletPath()+",token: "+token);
			Status status = new Status(request,response);
			status.setCode(HomiStatusCode.TOKEN_ABSENT);
			status.write();
		}
		return flag;
	}
}
